package com.smh.a11LockThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread extends Thread {
    static int ticket = 0;
    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();//上锁
            try {
                if (ticket >= 100) {
                    //lock.unlock();
                    break;//当结束时直接跳出循环了,但是忘记开锁,导致其他进程只能无限等待
                } else {
                    Thread.sleep(10);
                    ticket++;
                    System.out.println(Thread.currentThread().getName() + "@" + ticket);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }





            /*synchronized (MyThread.class){
                if (ticket>=100){
                    break;
                }else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    ticket++;
                    System.out.println(Thread.currentThread().getName()+"@"+ticket);
                }
            }*/
        }

    }
    /*lock.lock();//上锁
                if (ticket>=100){
        break;
    }else {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        ticket++;
        System.out.println(Thread.currentThread().getName()+"@"+ticket);
    }
            lock.unlock();//开锁*/
}
